import { getUrlParams } from './utils';

// mock tableListDataSource
let tableListDataSource = [];
for (let i = 0; i < 46; i += 1) {
  tableListDataSource.push({
    sort: i,
    type: i % 10,
    show: i % 2,
    uid: '徐政涛',
    editTime: '2018-12-01 00:00:00',
  });
}

export function getRecommendTag(req, res, u) {
  let url = u;
  if (!url || Object.prototype.toString.call(url) !== '[object String]') {
    url = req.url; // eslint-disable-line
  }

  const params = getUrlParams(url);

  let dataSource = [...tableListDataSource];

  if (params.sorter) {
    const s = params.sorter.split('_');
    dataSource = dataSource.sort((prev, next) => {
      if (s[1] === 'descend') {
        return next[s[0]] - prev[s[0]];
      }
      return prev[s[0]] - next[s[0]];
    });
  }

  if (params.status) {
    const status = params.status.split(',');
    let filterDataSource = [];
    status.forEach((s) => {
      filterDataSource = filterDataSource.concat(
        [...dataSource].filter(data => parseInt(data.status, 10) === parseInt(s[0], 10))
      );
    });
    dataSource = filterDataSource;
  }

  if (params.no) {
    dataSource = dataSource.filter(data => data.no.indexOf(params.no) > -1);
  }

  let pageSize = 10;
  if (params.pageSize) {
    pageSize = params.pageSize * 1;
  }

  const result = {
    list: dataSource,
    pagination: {
      total: dataSource.length,
      pageSize,
      current: parseInt(params.currentPage, 10) || 1,
    },
  };

  if (res && res.json) {
    res.json(result);
  } else {
    return result;
  }
}

export function postRecommendTag(req, res, u, b) {
  let url = u;
  if (!url || Object.prototype.toString.call(url) !== '[object String]') {
    url = req.url; // eslint-disable-line
  }

  const body = (b && b.body) || req.body;
  // eslint-disable-next-line camelcase
  const { method, types, params } = body;

  switch (method) {
    /* eslint no-case-declarations:0 */
    case 'delete':
    // eslint-disable-next-line camelcase
      tableListDataSource = tableListDataSource.filter(item => types.indexOf(`${item.type},`) === -1);
      break;
    case 'post':
      let i = Math.ceil(Math.random() * 10000);
      if (params.type !== undefined) {
        tableListDataSource = tableListDataSource.filter(item => params.type != item.type);
        i = params.type;
      }
      tableListDataSource.unshift({
        sort: params.sort,
        type: params.type,
        show: params.show,
        uid: '徐政涛',
        editTime: '2018-12-01 00:00:00',
      });
      break;
    default:
      break;
  }

  const result = {
    list: tableListDataSource,
    pagination: {
      total: tableListDataSource.length,
    },
  };

  if (res && res.json) {
    res.json(result);
  } else {
    return result;
  }
}

export default {
  getRecommendTag,
  postRecommendTag,
};
